<template>
	<view class="equipment-manage">
		<gyd-navbar back-color="#fff" :title="title"></gyd-navbar>

		<view class="content">
			<view class="statistics-card">
				<view class="grid-item">
					<text class="label">总数</text>
					<text class="value">{{dataInfo.total}}</text>
				</view>
				<view class="grid-item" :class="params.current==1?'active':''" @click="changeTab(1)">
					<text class="label">已安装</text>
					<text class="value">{{dataInfo.installed_num}}</text>
				</view>
				<view class="grid-item" :class="params.current==2?'active':''" @click="changeTab(2)">
					<text class="label">未安装</text>
					<text class="value">{{dataInfo.notinstalled_num}}</text>
				</view>
			</view>

			<!--筛选-->
			<view class="filter-box">
				<view class="filter-item">
					<uni-data-select v-model="params.device_type" :localdata="deviceTypeList" @change="changeDeviceType"
						placeholder="设备类型"></uni-data-select>
				</view>
				<view class="filter-item">
					<uni-data-select v-model="params.device_model" :localdata="deviceModelList"
						@change="changeDeviceModel" placeholder="设备型号"></uni-data-select>
				</view>
				<view class="filter-item">
					<uni-data-select v-model="params.sales_method" :localdata="salesMethodList"
						@change="changeSalesMethod" placeholder="销售方式"></uni-data-select>
				</view>
				<view class="filter-item" v-if="params.current==1">
					<uni-data-select v-model="params.ad_position" :localdata="adPositionList" @change="changeAdPosition"
						placeholder="广告位置"></uni-data-select>
				</view>
			</view>
			<view class="filter-box" v-if="params.current==1">
				<view class="area-opt">
					<uni-data-select class="area-item" v-model="params.province" :localdata="provinceList"
						@change="getCity" placeholder="省查询"></uni-data-select>
					<uni-data-select class="area-item" v-model="params.city" :localdata="cityList" @change="getArea"
						placeholder="市查询"></uni-data-select>
					<uni-data-select class="area-item" v-model="params.area" :localdata="areaList" @change="getDataList"
						placeholder="区县查询"></uni-data-select>
				</view>
			</view>

			<view class="device-card" v-for="(item,index) in list" :key="index">
				<view class="header">
					<text class="NO">编号：{{item.device_no}}</text>
					<text class="count">{{item.device_type_str}}</text>
				</view>
				<view class="bd">
					<view class="cell" v-if="item.status==1 || item.status==2">
						<view class="cell-item">
							<text class="label">客户信息：</text>
							<text class="value">{{item.customer.customer_name}} {{item.customer.mobile}}</text>
						</view>
						<view class="cell-item">
							<text class="label">安装时间：</text>
							<text class="value">{{item.create_time}}</text>
						</view>
						<view class="cell-item">
							<text class="label">安装地点：</text>
							<text class="value">{{item.customer.format_address ?? '---'}}</text>
						</view>
						<view class="cell-item">
							<text class="label">到期时间：</text>
							<text class="value">{{item.expiration_time}}</text>
						</view>
					</view>

					<view class="cell" v-if="item.status==-1">
						<view class="cell-item">
							<text class="label">设备名称：</text>
							<text class="value">{{item.name}}</text>
						</view>
					</view>
				</view>

				<view class="footer-btn">
					<view class="btn-group" v-if="item.status==1 || item.status==2">
						<u-button class="btn" type="error" size="small" @click="unbindCustomer(item)">解绑客户</u-button>
						<u-button class="btn" type="success" size="small" @click="bindCustomer(item)">更换客户</u-button>
						<u-button class="btn" type="warning" size="small" @click="callback(item)">回拨</u-button>
						<u-button class="btn" type="primary" size="small" @click="renew(item)">续费</u-button>
					</view>

					<view class="btn-group" v-if="item.status==-1">
						<u-button class="btn" type="primary" size="small" @click="bindCustomer(item)">绑定客户</u-button>
						<u-button class="btn" type="warning" size="small" @click="callback(item)">回拨</u-button>
					</view>
				</view>
			</view>

			<view class="device-card" style="text-align: center;" v-if="list.length===0">暂无数据</view>
		</view>

		<!-- 绑定客户弹窗 -->
		<uni-popup background-color="#fff" type="center" ref="shelfRef">
			<view class="show-panel">
				<view class="show-title">绑定客户</view>
				<view class="form">
					<view class="form-item">设备类型：{{deviceInfo.device_type_str}}</view>
					<view class="form-item">设备名称：{{deviceInfo.name}}</view>
					<view class="form-item" v-if="deviceInfo.device_type==1">设备型号：{{deviceInfo.grids_num}}#</view>
					<view class="form-item">设备编号：{{deviceInfo.device_no}}</view>
					<view class="form-item" v-if="formData.old_cust_id && deviceCustomer">
						原客户：{{deviceCustomer.customer.customer_name}}({{deviceCustomer.customer.mobile}})</view>
					<view class="form-item">待绑定客户：<cus-selects :closeSelect.sync="false" :data="customerList"
							:value="formData.customer_id" placeholder="请输入关键字搜索" @change="changeCustomer"
							:clearable="true" :filterable="true" :searchType='1'></cus-selects>
					</view>
					<template v-if="deviceInfo.device_type==1">
						<view class="form-item">
							使用架子格数
							<u-input type="number" border="surround" class="value" placeholder="请输入"
								v-model="formData.use_grids_num" />
						</view>
						<view class="form-item">
							送水预警值
							<u-input type="number" border="surround" class="value" placeholder="请输入"
								v-model="formData.water_threshold" />
						</view>
					</template>
					<view class="form-item">
						设备位置描述
						<u-textarea class="value" border="surround" placeholder="请输入"
							v-model="formData.location_desc"></u-textarea>
					</view>
				</view>
			</view>
			<view class="footer">
				<view class="btn-group">
					<u-button class="btn" type="primary" size="small" plain @click="submit()">确认绑定</u-button>
					<u-button class="btn" type="info" size="small" plain @click="shelfRef.close()">取消绑定</u-button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import util from '@/utils/util';
	import {
		ref,
		reactive,
		toRefs,
		inject,
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady,
		onPullDownRefresh,
		onReachBottom,
	} from '@dcloudio/uni-app';
	import cusSelects from '@/components/cus-selects-fan/cus-selects-fan.vue';

	const state = reactive({
		title: '设备管理',
		themeColor: cache.get('themeColor'),
		imgHost: util.requestUrl(),
		dataInfo: {
			total: 0,
			installed_num: 0,
			notinstalled_num: 0,
		},
		params: {
			current: 1,
			flag: 'agent',
			device_type: 0,
			device_model: 0,
			sales_method: 0,
			ad_position: 0,
			province: 0,
			city: 0,
			area: 0,
		},
		isMore: true,
		list: [],
		deviceInfo: {},
		deviceCustomer: {},
		formData: {
			device_id: 0,
			old_cust_id: 0,
			customer_id: 0,
			use_grids_num: 0,
			water_threshold: 0,
			location_desc: '',
		}
	});

	const deviceTypeList = ref([]);
	const deviceModelList = ref([]);
	const holderTypeList = ref([]);
	const salesMethodList = ref([]);
	const adPositionList = ref([]);
	const provinceList = ref([]);
	const cityList = ref([]);
	const areaList = ref([]);

	const shelfRef = ref(null);
	const customerList = ref([]);

	//在页面所有元素加载完成后执行（只执行一次）
	onLoad((opt) => {
		console.log('onLoad');
		if (opt.hasOwnProperty('flag')) {
			console.log('传递参数', opt.flag);
			state.params.flag = opt.flag;
		}
		initData();
	});

	//在页面由不可见变为可见时执行（只要页面显示都会执行）
	onShow(() => {
		console.log('onShow');
	})

	//在页面解析完成之后执行
	onReady(() => {
		console.log('onReady');
	})

	onPullDownRefresh(() => {
		console.log('下拉刷新');
		setTimeout(() => {
			uni.stopPullDownRefresh();
		}, 1000);
		search();
	})

	onReachBottom(() => {
		console.log('触底加载更多');
		getDataList();
	})

	function initData() {
		getData();
		getDataList();
		getSearchCriteria();
		getProvince();
	}

	function getData() {
		request.get("equipment/index", state.params).then(res => {
			console.log('数据', res);
			state.dataInfo = res.data;
		})
	}

	function getDataList() {
		if (!state.isMore) {
			util.showTip('没有更多了');
			return;
		}
		state.params.skip = state.list.length;
		request.get("equipment/list", state.params).then(res => {
			console.log('设备列表', res);
			state.isMore = res.data.is_more;
			if (state.list.length == 0) {
				state.list = res.data.list;
			} else {
				state.list = state.list.concat(res.data.list);
			}
		})
	}

	function getSearchCriteria() {
		request.get("filters.equipment/getSelectData", state.params).then(res => {
			console.log('选择数据', res);
			deviceTypeList.value = res.data.deviceTypeList;
			deviceModelList.value = res.data.deviceModelList;
			adPositionList.value = res.data.adPositionList;

			let sales_method_list = res.data.salesMethodList;
			sales_method_list.forEach(item => {
				if (item.value != -1) {
					salesMethodList.value.push(item);
				}
			})
		})
	}

	function search() {
		state.isMore = true;
		state.list = [];
		getDataList();
	}

	function changeTab(type) {
		state.params.current = type;
		search();
	}

	function changeDeviceType(e) {
		console.log('设备类型', e);
		state.params.device_type = e;
		search();
	}

	function changeDeviceModel(e) {
		console.log('设备型号', e);
		state.params.device_model = e;
		search();
	}

	function changeSalesMethod(e) {
		console.log('销售方式', e);
		state.params.sales_method = e;
		search();
	}

	function changeAdPosition(e) {
		console.log('广告位置', e);
		state.params.ad_position = e;
	}

	function getProvince() {
		request.get('address/getAreaByPid', {
			pid: 0
		}).then(res => {
			provinceList.value = res.data;
			provinceList.value.forEach(item => {
				item.text = item.label; // 添加 text 属性
				delete item.label; // 删除 label 属性
			})
		})
	}

	function getCity() {
		if (!state.params.province) {
			return
		}
		request.get('address/getAreaByPid', {
			pid: state.params.province
		}).then(res => {
			cityList.value = res.data
			cityList.value.forEach(item => {
				item.text = item.label; // 添加 text 属性
				delete item.label; // 删除 label 属性
			})
			search();
		})
	}

	function getArea() {
		if (!state.params.city) {
			return
		}
		request.get('address/getAreaByPid', {
			pid: state.params.city
		}).then(res => {
			areaList.value = res.data
			areaList.value.forEach(item => {
				item.text = item.label; // 添加 text 属性
				delete item.label; // 删除 label 属性
			})
			search();
		})
	}

	function callback(item) {
		uni.showModal({
			title: '温馨提示',
			content: '确认要回拨该设备吗？',
			success: function(res) {
				if (res.confirm) {
					console.log('用户点击确定');
					request.post('', {}).then(res => {
						console.log('回拨结果', res);
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}

	function renew(item) {
		util.showTip('功能开发中');
	}

	function unbindCustomer(item) {
		uni.showModal({
			title: '温馨提示',
			content: '确认要解绑客户吗？',
			success: function(res) {
				if (res.confirm) {
					console.log('用户点击确定');
					request.post('equipment/unbindCustomer', {
						device_id: item.id
					}).then(res => {
						console.log('设备绑定结果', res);
						util.showTip(res.msg);
						if (res.code == 1) {
							setTimeout(() => {
								getData();
								search();
							}, 800);
						}
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}

	function bindCustomer(item) {
		console.log('设备信息', item);
		state.deviceInfo = item;
		state.formData.device_id = item.id;
		getCustomerList();
		if (item.customer) {
			state.formData.old_cust_id = item.customer.id;
			getDeviceCustomer();
		} else {
			state.formData.old_cust_id = 0;
			state.deviceCustomer = {};
			state.formData.use_grids_num = item.grids_num;
			state.formData.water_threshold = Math.floor(item.grids_num / 2);
		}
		shelfRef.value.open();
	}

	function getDeviceCustomer() {
		request.get('agent.equipment/getDeviceCustomer', {
			device_id: state.formData.device_id
		}).then(res => {
			console.log('原设备绑定客户', res);
			state.deviceCustomer = res.data;
			state.formData.use_grids_num = state.deviceCustomer.grids_num;
			state.formData.water_threshold = state.deviceCustomer.water_threshold;
		})
	}

	function getCustomerList() {
		request.get('agent.customer/getCustomerList').then(res => {
			console.log('客户列表', res);
			let data = res.data;
			data.forEach((item, index) => {
				customerList.value.push({
					text: 'ID:' + item.id + ',名称:' + item.customer_name + ',手机:' + item.mobile,
					label: 'ID:' + item.id + ',名称:' + item.customer_name + ',手机:' + item.mobile,
					value: item.id + ''
				});
			})
		})
	}

	function changeCustomer(e) {
		console.log('选择客户', e);
		state.formData.customer_id = e;
	}

	function submit() {
		console.log('提交');
		if (state.deviceInfo.device_type == 1) {
			if (state.formData.use_grids_num <= 0 || state.formData.use_grids_num > 12) {
				util.showTip('请输入正确的水架使用格数');
				return;
			}
			if (state.formData.use_grids_num > state.deviceInfo.grids_num) {
				util.showTip('使用数量不能超过水架设备格数');
				return;
			}
			if (!state.formData.water_threshold) {
				util.showTip('请输入送水预警值');
				return;
			}
			if (state.formData.water_threshold <= 1 || state.formData.water_threshold >= state.deviceInfo.grids_num) {
				util.showTip('请输入合理的送水预警值');
				return;
			}
		}
		if (!state.formData.customer_id) {
			util.showTip('请选择需要绑定的客户');
			return;
		}
		if (state.formData.old_cust_id && (state.formData.customer_id == state.formData.old_cust_id)) {
			util.showTip('需要绑定的客户和原客户不能一致');
			return;
		}

		request.post('equipment/bindCustomer', state.formData).then(res => {
			console.log('设备绑定结果', res);
			shelfRef.value.close();
			util.showTip(res.msg);
			if (res.code == 1) {
				setTimeout(() => {
					getData();
					search();
				}, 800);
			}
		});
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	}

	function pageTabRoute(url) {
		uni.reLaunch({
			url
		});
	}

	const {
		title,
		themeColor,
		imgHost,
		dataInfo,
		params,
		isMore,
		list,
		deviceInfo,
		deviceCustomer,
		formData,
	} = toRefs(state);
</script>

<style lang="scss">
	page {
		background: linear-gradient(180deg, #eff6ff 0%, #f7f7fb 54%);
	}

	.equipment-manage {
		padding-bottom: calc(100rpx + env(safe-area-inset-bottom));

		.content {
			padding: $m24;

			.statistics-card {
				display: flex;
				flex-wrap: wrap;
				padding: 12rpx;
				background-color: #fff;
				border-radius: $radius-16;
				text-align: center;

				.grid-item {
					// display: flex;
					// flex-direction: column;
					flex: 1;

					.label {
						font-size: $font-28;
						// color: $tips-color;
					}

					.value {
						font-size: $font-36;
						color: $primary-color;
						font-weight: 500;
						margin-left: 24rpx;
					}
				}

				.active {
					.label {
						color: $primary-color;
					}
				}
			}

			.status-box {
				padding: $m24 0;
			}

			.filter-box {
				display: flex;
				align-items: center;
				padding: $m24 0;

				.filter-item {
					@include f-center;
					margin-right: $m20;
					padding: .1em .1em;
					background-color: #fff;
					border-radius: $radius-8;
					width: 200rpx;

					.label {
						margin-right: 10rpx;
					}
				}

				.area-opt {
					display: flex;
					width: auto;

					.area-item {
						@include f-center;
						margin-right: $m20;
						padding: .2em .6em;
						background-color: #fff;
						border-radius: $radius-8;
						width: 210rpx;
					}
				}
			}

			.device-card {
				margin-bottom: $m24;
				padding: 0 $m24;
				background-color: #fff;
				border-radius: $radius-16;

				&:last-child {
					margin-bottom: 0;
				}

				.header {
					@include f-between($align: center);
					padding: $m24 0;
					border-bottom: 1rpx solid $border-color;

					.NO {}

					.count {}

					.status {
						color: #1A79F9;
					}
				}

				.bd {
					padding: $m24 0;

					.cell {
						.cell-item {
							@include f-between;
							font-size: $font-24;
							padding: 4rpx 0;

							.label {
								color: $tips-color;
							}

							.value {
								flex: 1;
								color: $primary-color;
							}
						}
					}
				}

				.footer-btn {
					@include f-between($align: center);
					padding: $m24 0;
					border-top: 1rpx solid $border-color;

					.btn-group {
						display: flex;
						justify-content: flex-end;
						flex: 1;
					}
				}
			}
		}
	}

	.show-panel {
		padding: $m24;
		width: 560rpx;

		.show-title {
			width: 100%;
			line-height: 50rpx;
			text-align: center;
			font-size: 28rpx;
			font-weight: 800;
			color: #000;
		}

		.form {
			padding: $m24;

			.form-item {
				line-height: 60rpx;
				font-size: 24rpx;
				color: #000;
				display: flex;
				flex-direction: row;
				flex-wrap: wrap;
				align-items: flex-start;
				justify-content: space-between;

				.label {
					// width: 180rpx;
				}

				.value {
					margin: 5rpx 0 5rpx 24rpx;
					flex: 1;
				}
			}
		}

		.footer {
			.btn-group {
				display: flex;
				justify-content: flex-end;
				flex: 1;

				.btn {}
			}
		}
	}
</style>